package com.lanxin.xxform.services.impls;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanxin.xxform.aspects.exceptions.ServiceException;
import com.lanxin.xxform.beans.Paper;
import com.lanxin.xxform.mappers.PaperMapper;
import com.lanxin.xxform.services.PaperService;
import com.lanxin.xxform.tools.JetCriteria;
import com.lanxin.xxform.tools.JetDate;

@Service
public class PaperServiceImpl implements PaperService {

    @Autowired
    private PaperMapper paperMapper;

    @Override
    public int save(Paper paper) {
        if (paper.getId() == 0) {
            paper.setCreateTime(JetDate.timeNow());
            return paperMapper.insert(paper);
        } else {
            Paper p = get(paper.getId());
            p.setTitle(paper.getTitle());
            p.setNote(paper.getNote());
            p.setUpdateTime(JetDate.timeNow());
            p.setStatus(paper.getStatus());
            return paperMapper.update(paper);
        }
    }

    @Override
    public Paper get(long id) {
        Paper paper = paperMapper.find(id);
        if (paper == null) {
            throw new ServiceException("问卷信息不存在");
        }
        return paper;
    }

    /**
     * 搜索条件
     * @param keyword
     * @param status
     * @param uid
     * @return
     */
    private JetCriteria searchCondition(String keyword, int status, long uid) {
        JetCriteria criteria = new JetCriteria();
        criteria.addLike("title", keyword);
        if (status > 0) {
            criteria.add("status", status);
        }
        if (uid > 0) {
            criteria.add("uid", uid);
        }
        return criteria;
    }

    @Override
    public int getCount(String keyword, int status, long uid) {
        return paperMapper.count(searchCondition(keyword, status, uid));
    }

    @Override
    public List<Paper> getList(int offset, int limit, String keyword, int status, long uid) {
        JetCriteria criteria = searchCondition(keyword, status, uid);
        criteria.setPage(offset, limit);
        criteria.orderBy("id", JetCriteria.ORDER_DESC);
        return paperMapper.findAll(criteria);
    }

    @Override
    public int delete(long id, long uid) {
        Paper paper = get(id);
        if (paper.getUid() != uid) {
            throw new ServiceException("操作身份不匹配");
        }
        return paperMapper.delete(id);
    }
    
}
